/**
 * Created by Administrator on 2017/4/25.
 */


require('../../util/class');
exports.GameAI = Class.extend({
    _player: null,
    _actions: {},
    _curRoute: null,

    init: function(player) {
        this._player = player;
        this._actions = {};
        this._curRoute = "";
    },

    getPlayer: function() {
        return this._player;
    },

    getRoom: function() {
        return this._player.getRoom();
    },

    setAction: function(ms, handler) {
        var route = this._curRoute;
        this._actions[route] = setTimeout(function() {
            handler.call(this);
            delete this._actions[route];
        }.bind(this), ms);
    },

    execute: function(route, msg) {
        var handler = this[route];
        if (!handler) {
            return;
        }

        this._curRoute = route;
        handler.call(this, msg);
    },

    onPlayerEnter: function(msg) {
        if (this.getPlayer().isReady()) {
            return;
        }

        if (msg.playerIndex != this._player.getIndex()) {
            return;
        }

        if (this.getRoom().getReadyPlayerCount() > 0) {
            this.setAction(Ext.randRange(1000, 5000), function() {
                this.getRoom().callHandler("handlePlayerReady", this.getPlayer(), {});
            });
        }
    },

    onPlayerReady: function(msg) {
        if (this.getPlayer().isReady()) {
            return;
        }

        this.setAction(Ext.randRange(1000, 5000), function() {
            this.getRoom().callHandler("handlePlayerReady", this.getPlayer(), {});
        });
    },

    onPlayerQuitRoom: function(msg) {
        this.setAction(Ext.randRange(1000, 3000), function() {
            var room = this.getRoom();
            if (room.getRealPlayerCount() < 1) {
                this.getRoom().callHandler("handleQuitRoom", this.getPlayer(), {});
            }
        });
    }
});